<style>
    .supplierContactsForm .layui-form-label{
        width: 110px;
    }
    .supplierContactsForm .layui-input-block{
        margin-left: 140px;
    }
    .import {
        opacity: 0;
        position: absolute;
        width: 69px;
        height: 38px;
        margin-left: -10px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label">供应商名称：</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" name="corporateName" placeholder="供应商名称" autocomplete="off"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">联系人姓名：</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" name="contactName" placeholder="联系人姓名">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">联系人电话：</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" name="phoneNumber" placeholder="联系人电话">
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="productDetailBtnImport" class="layui-btn icon-btn color-reseda">
                                <input id="uploaderInput" type="file" name="file" class="import" accept=".xls,.xlsx" />
                                导入
                            </button>
                            <button id="supplierContactsBtnAdd" class="layui-btn icon-btn color-reseda" type="button">添加</button>
                        </div>
                        <div class="lay-btn-rt">
                            <button id="productDetailBtnTemplate" class="layui-btn icon-btn color-green">模板下载</button>
                            <button id="SupplierContactsBtnDel" class="layui-btn icon-btn layui-btn-danger">批量删除</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="supplierContactsTable" lay-filter="supplierContactsTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="supplierContactsTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="details">详情</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="supplierContactsForm">
    <form lay-filter="supplierContactsForm" class="layui-form supplierContactsForm model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">供应商公司名称</label>
            <div class="layui-input-block">
                <select name="corporateId" lay-verify="required" required id="corporateId"></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">联系人姓名</label>
            <div class="layui-input-block">
                <input name="contactName" placeholder="请输入联系人姓名" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">联系人电话</label>
            <div class="layui-input-block">
                <input name="phoneNumber" placeholder="请输入联系人电话" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">职务</label>
            <div class="layui-input-block">
                <input name="job" placeholder="请输入职务" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">身份证号码</label>
            <div class="layui-input-block">
                <input name="cardNo" placeholder="请输入身份证号码" type="text" class="layui-input"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">证件扫描件</label>
            <div class="layui-input-block">
                <div id="btnUploadCredentials_path" class="uploadImgStyle" style="margin: 0;"></div>
                <div id="btnUploadCredentials" class="layui-btn" style="float: left;"><i class="layui-icon">&#xe681;</i>上传</div>
                <input name="cardPic" type="hidden" class="layui-input" lay-verify="" id="cardPic"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">名片扫描件</label>
            <div class="layui-input-block">
                <div id="btnUploadDviceAppendix_path" class="uploadImgStyle" style="margin: 0;"></div>
                <div id="btnUploadDviceAppendix" class="layui-btn" style="float: left;"><i class="layui-icon">&#xe681;</i>上传</div>
                <input name="callingCardPic" type="hidden" class="layui-input" lay-verify="" id="callingCardPic"/>
            </div>
        </div>
        <div class="layui-form-item" style="margin-left: 70px">
            <div class="layui-col-xs4">
                <label class="layui-form-label" style="width: 40px;">省</label>
                <div class="layui-input-block" style="margin-left: 70px">
                    <select name="provinceId" id="provinceId" lay-filter="provinceId"></select>
                </div>
            </div>
            <div class="layui-col-xs4">
                <label class="layui-form-label" style="width: 40px;">市</label>
                <div class="layui-input-block" style="margin-left: 70px">
                    <select name="cityId" id="cityId" lay-filter="cityId"></select>
                </div>
            </div>
            <div class="layui-col-xs4">
                <label class="layui-form-label" style="width: 40px;">区/县</label>
                <div class="layui-input-block" style="margin-left: 70px">
                    <select name="areaId" id="areaId" lay-filter="areaId"></select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">联系地址</label>
            <div class="layui-input-block">
                <input name="contactAddress" placeholder="请输入联系地址" type="text" class="layui-input"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱地址</label>
            <div class="layui-input-block">
                <input name="email" placeholder="请输入邮箱地址" type="text" class="layui-input"/>
            </div>
        </div>
        <div class="layui-form-item text-right" style="padding: 5px 0;">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="supplierContactsFormSubmit" id="supplierContactsFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin','upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;

        // 渲染表格
        var insTb = table.render({
            elem: '#supplierContactsTable',
            url: config.base + 'enterprise/purchase/admin/supplierContacts/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'checkbox'}
                ,{field: 'number', title: '序号', width: 60, type: 'numbers'}
                ,{field: 'contactName', align: "center", title: '联系人姓名'}
                ,{field: 'phoneNumber', align: "center", title: '联系人电话'}
                ,{field: 'job', align: "center", title: '职务'}
                ,{field: 'corporateName', align: "center", title: '供应商公司名称'}
                ,{field: 'email', align: "center", title: '邮箱'}
                ,{field: 'creatorName', align: "center", title: '添加人'}
                ,{field: 'createTime', align: "center", title: '创建时间'}
                ,{align: 'center', toolbar: '#supplierContactsTableBar', title: '操作', width: 200}
            ]],
        });

        var flag=true;
        // 工具条点击事件
        table.on('tool(supplierContactsTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                flag=true;
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            }else if (obj.event === 'details') { // 详情
                flag=false;
                showEditModel(data);
            }
        });

        //监听排序
        table.on('sort(supplierContactsTable)', function(obj){
            table.reload('supplierContactsTable', {
                initSort: obj
                ,where: {
                    sort: obj.field
                    ,order: obj.type
                }
            });
        });

        // 添加按钮点击事件
        $('#supplierContactsBtnAdd').click(function () {
            showEditModel();
        });

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '760px',
                title: data ? (flag?'修改供应商联系人信息':"供应商联系人信息详情") : '添加供应商联系人信息',
                content: $('#supplierContactsForm').html(),
                success: function () {
                    if (data&&!flag){//详情
                        $("#btnUploadCredentials_path").html("<img src='"+data.cardPic+"' style='margin-right: 10px;'/>")
                        $("#btnUploadDviceAppendix_path").html("<img src='"+data.callingCardPic+"' style='margin-right: 10px;'/>")
                        layer.photos({
                            photos: '.uploadImgStyle'
                            ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                        });
                        admin.reqSync('enterprise/purchase/admin/supplierInfoPass/list?page=1&limit=99999', {}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择供应商", "corporateId",1)
                            }
                        }, 'GET');
                        admin.reqSync('enterprisecab/area/admin/area/getProvince', {}, function (res) {
                            if (200 == res.code) {
                                loadSelectHtml(res.data, "请选择省份", "provinceId", 0);
                            }
                        }, 'GET', true);

                        admin.reqSync('enterprisecab/area/admin/area/getCity?parentId=' + data.provinceId, {}, function (res) {
                            if (200 == res.code) {
                                loadSelectHtml(res.data, "请选择城市", "cityId", 0);
                            }
                        }, 'GET', true);

                        admin.reqSync('enterprisecab/area/admin/area/getArea?parentId=' + data.cityId, {}, function (res) {
                            if (200 == res.code) {
                                loadSelectHtml(res.data, "请选择区/县", "areaId", 0);
                            }
                        }, 'GET', true);
                        $('[lay-filter="supplierContactsForm"] input').attr("disabled", '');
                        $('[lay-filter="supplierContactsForm"] input').attr("placeholder", ' ');
                        $('[lay-filter="supplierContactsForm"] select').attr("disabled", '');

                        $('#supplierContactsFormSubmit').css("display", "none")
                        $('#btnUploadCredentials').css("display", "none")
                        $('#btnUploadDviceAppendix').css("display", "none")


                    } else if(data&&flag){//修改
                        $("#btnUploadCredentials_path").html("<img src='"+data.cardPic+"' style='margin-right: 10px;'/>")
                        $("#btnUploadDviceAppendix_path").html("<img src='"+data.callingCardPic+"' style='margin-right: 10px;'/>")
                        layer.photos({
                            photos: '.uploadImgStyle'
                            ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                        });
                        admin.reqSync('enterprise/purchase/admin/supplierInfoPass/list?page=1&limit=99999', {}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择供应商", "corporateId",1)
                            }
                        }, 'GET');
                        admin.reqSync('enterprisecab/area/admin/area/getProvince', {}, function (res) {
                            if (200 == res.code) {
                                loadSelectHtml(res.data, "请选择省份", "provinceId", 0);
                            }
                        }, 'GET', true);

                        admin.reqSync('enterprisecab/area/admin/area/getCity?parentId=' + data.provinceId, {}, function (res) {
                            if (200 == res.code) {
                                loadSelectHtml(res.data, "请选择城市", "cityId", 0);
                            }
                        }, 'GET', true);

                        admin.reqSync('enterprisecab/area/admin/area/getArea?parentId=' + data.cityId, {}, function (res) {
                            if (200 == res.code) {
                                loadSelectHtml(res.data, "请选择区/县", "areaId", 0);
                            }
                        }, 'GET', true);
                    }else{
                        //已通过审核供应商名称
                        admin.reqSync('enterprise/purchase/admin/supplierInfoPass/list?page=1&limit=99999', {}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择供应商", "corporateId",1)
                            }
                        }, 'GET');
                        var selectArea = function (city) {
                            admin.req('enterprisecab/area/admin/area/getArea?parentId=' + city, {}, function (res) {
                                layer.closeAll('loading');
                                if (200 == res.code) {
                                    loadSelectHtml(res.data, "请选择区/县", "areaId", 0);
                                }
                            }, 'GET');
                        }
                        var selectCity = function (province) {
                            admin.req('enterprisecab/area/admin/area/getCity?parentId=' + province, {}, function (res) {
                                layer.closeAll('loading');
                                if (200 == res.code) {
                                    loadSelectHtml(res.data, "请选择市", "cityId", 0);
                                }
                            }, 'GET');
                        }
                        // 获取省区域信息
                        admin.req('enterprisecab/area/admin/area/getProvince', {}, function (res) {

                            if (200 == res.code) {
                                loadSelectHtml(res.data, "请选择省份", "provinceId", 0);
                            }
                        }, 'GET', true);
                        form.on('select(provinceId)', function (data) {
                            $("#cityId").empty();
                            $('#areaId').empty();
                            // 获取市区域信息
                            if (data.value != '') {
                                selectCity(data.value);
                            }
                        });
                        form.on('select(cityId)', function (data) {
                            $('#areaId').empty();
                            // 获取区县区域信息
                            if (data.value != '') {
                                selectArea(data.value);
                            }
                        });
                    }
                    form.val('supplierContactsForm', data);
                    $('#btnUploadCredentials').click(uploadImg('btnUploadCredentials','btnUploadCredentials_path','cardPic'))
                    $('#btnUploadDviceAppendix').click(uploadImg('btnUploadDviceAppendix','btnUploadDviceAppendix_path','callingCardPic'))
                    // 表单提交事件
                    form.on('submit(supplierContactsFormSubmit)', function (d) {
                        layer.load(2);
                        admin.req(data ? 'enterprise/purchase/admin/supplierContacts/update' : 'enterprise/purchase/admin/supplierContacts/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('supplierContactsTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/purchase/admin/supplierContacts/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
                // insTb.reload();
            });
        }


        $('#SupplierContactsBtnDel').click(function () {
            var checkRows = table.checkStatus('supplierContactsTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要删除的数据', {icon: 2});
            } else {
                var ids='';
                checkRows.data.forEach(item=>{
                    ids+=item.id+','
                })
                // delBatch(ids)
                console.log("ids",ids);
            }
        });

        function delBatch(ids){
            admin.req('enterprise/purchase/admin/supplierContacts/delBatch', {ids:ids}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'POST');
            insTb.reload();
        }


        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, 'data');
        });

        // 上传
        function uploadImg(_elem, pathId, inputId) {
            upload.render({
                elem: '#' + _elem
                , url: config.upload_url + 'uploadFile'
                , data: {}
                , accept: 'file'
                , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx'
                , headers: { Authorization: 'Bearer ' + config.getToken() }
                , done: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg || "上传成功", { icon: 1 });
                        let imagUrl = res.data.url;
                        $('#' + pathId).html('<img src="' +imagUrl + '"/>');
                        $('#' + inputId).val(imagUrl);
                    } else if (res.code == 502) {
                        return location.replace('admin/login.html');
                    } else {
                        layer.msg(res.msg || "上传失败", { icon: 2 });
                    }
                }
            });
        }

        // option渲染
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type === 0) {
                    html += `<option value='${data[i].id}'>${data[i].name}</option>`;
                } else {
                    html += `<option value='${data[i].id}'>${data[i].corporateName}</option>`;

                }
            }
            $("form select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }

        // 导出excel
        $('#supplierContactsBtnExport').click(function () {
            var checkRows = table.checkStatus('supplierContactsTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

        // 模板下载
        $('#productDetailBtnTemplate').click(function () {
            window.location.href = config.base + 'enterprise/purchase/admin/supplierContacts/template';
        });

        //导入excel
        $('#uploaderInput').on('change', function (e) {
            layer.load(2);
            var formData = new FormData();
            var files = e.target.files;
            let that = $(this);
            formData.append('file', files[0]);
            formData.append('name', files[0].name); //这个地方可以传递多个参数
            $.ajax({
                url: config.base + 'enterprise/purchase/admin/supplierContacts/importExcel',
                data: formData,
                headers: { Authorization: 'Bearer ' + config.getToken() },
                type: 'POST',
                processData: false,
                contentType: false,
                success: function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, { icon: 1 });
                        layer.closeAll('page');
                        setTimeout((_) => {
                            location.reload();
                        }, 1000);
                    } else {
                        layer.msg(res.msg, { icon: 2 });
                    }
                    that.val('');
                },
            });
        });
    });
</script>